package com.xiaozhen.blog.controller;

import com.xiaozhen.blog.entity.Blog;
import com.xiaozhen.blog.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.Set;

/**
 * @create 2023-05-07 21:06
 */
@Controller
public class ApiController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BlogService blogService;

    /**
     * 创建定时任务，每天凌晨 3 点执行一次
     */
    @Scheduled(cron = "30 * * * * ?")
    private void blogViews(){
        System.out.println("---------------------定时任务开始执行----------------------");
        // 获取 redis 中博客浏览次数的 key
        Set<String> keys = redisTemplate.keys("uvBlog:blog" + "*");
        for (String key : keys){
            // 获取博客 id
            String blogId = key.substring(11);
            System.out.println(blogId);
            // 获取博客浏览量
            Integer views = (Integer) redisTemplate.opsForValue().get(key);

            // 更新博客浏览量
            Blog blog = blogService.getById(blogId);
            blog.setViews(views);
            // 更新成功删除 key
            if (blogService.updateById(blog)){
                redisTemplate.delete(key);
            };
        }
        // 将数据库中的博客浏览次数存入 redis
        List<Blog> blogList = blogService.list(null);
        for (Blog blog : blogList){
            String blogId = String.valueOf(blog.getId());
            Integer views = blog.getViews();
            String redisKey = "uvBlog:blogId_" + blogId;
            redisTemplate.opsForValue().set(redisKey,views);
        }
    }
}
